package gnetwork

type TcpPackServe struct {
	*TcpServe
	headerSize int
	regulator  ITcpPackRegulator
}

func (self *TcpPackServe) rHandle(connId int32) {

	cItem, ok := self.tackOutConn(connId)
	if !ok {
		panic("system failed.")
	}

	var headerBuf []byte = nil
	if self.headerSize > 0 {
		headerBuf = make([]byte, self.headerSize)
	}

	var shrinkCount = 0

	var bufOffset = 0
	var packLen = -1
	var content = make([]byte, defaultBufSize)
exit:
	for {
		//读取一个包
		if headerBuf != nil {
			n, err := cItem.conn.Read(headerBuf[bufOffset:self.headerSize])

			if err != nil {
				self.cb.OnError(err)
				break exit
			}

			bufOffset += n
			if bufOffset != self.headerSize {
				//重新读取
				continue
			}

			packLen, err = self.regulator.ParserPackHeader(headerBuf)
			if err != nil {
				self.cb.OnError(err)
				break exit
			}

			if packLen == 0 {
				panic("system failed!")
			}

			var l = len(content)

			//临时方案为10
			if shrinkCount > 10 {
				//收缩至1/2
				l = l / 2
				if l < packLen {
					l = packLen
				}
				content = make([]byte, l)
				shrinkCount = 0
			}

			if l < packLen {
				content = make([]byte, packLen)
			} else {
				//增加收缩标识
				shrinkCount++
			}

			bufOffset = 0
			for bufOffset != packLen {
				readLen, err := cItem.conn.Read(content[bufOffset : packLen-bufOffset])
				if err != nil {
					self.cb.OnError(err)
					break exit
				}

				bufOffset += readLen
			}

			err = self.cb.OnReceived(connId, content[:bufOffset])
			if err != nil {
				self.cb.OnError(err)
				break exit
			}
		} else if packLen == -1 {
			//此时没有设置包头长度，则以普通tcp对待
			readLen, err := cItem.conn.Read(content)
			if err != nil {
				self.cb.OnError(err)
				break exit
			}
			err = self.cb.OnReceived(connId, content[bufOffset:readLen])
			if err != nil {
				self.cb.OnError(err)
				break exit
			}
		}
		bufOffset = 0
	}

	self.evLoop.PostMsg(close, connId)
}

//func (self *TcpPackServe) wHandle(connId int32, data []byte) {
//	self.TcpServe.wHandle(connId, data)
//}

func (self *TcpPackServe) SendData(connId int32, data []byte) {
	buf := self.regulator.BuildPackData(data)
	self.TcpServe.SendData(connId, buf)
}

func (self *TcpPackServe) SyncSendData(connId int32, data []byte) bool {
	buf := self.regulator.BuildPackData(data)
	return self.TcpServe.SyncSendData(connId, buf)
}

func NewTcpPackServe(tcp *TcpServe, hSize int, regulator ITcpPackRegulator) *TcpPackServe {
	var t = &TcpPackServe{
		TcpServe:   tcp,
		headerSize: hSize,
		regulator:  regulator,
	}
	//重置接口
	tcp.IOHandle = t
	return t
}
